import type { App } from 'vue'
import { UseModuleType } from '@apps/_share/enums'
import { useInitApp } from '@apps/_share/hooks/initApp'
import useMicroStore from '@apps/_share/store/micro'
import { isMicro } from '@apps/_share/utils'
import { APP_CODE, FIRST_SCREEN_LOADING_TITLE, TITLE } from './settings'

export default async function init(app: App) {
  const {
    installModules,
    setUserInfo,
    setLanguages,
    setApps,
    // setProjects,
    setTitle,
    setTheme,
    setWritingMode,
    setFirstScreenLoading,
    cancelFirstScreenLoading,
  } = useInitApp(app)

  if (isMicro(window.parent.location.pathname)) {
    cancelFirstScreenLoading()
  }
  else {
    setFirstScreenLoading({ title: FIRST_SCREEN_LOADING_TITLE })
  }

  try {
    installModules([
      UseModuleType.PINIA,
      UseModuleType.UI,
      UseModuleType.I18N,
    ], () => {
      Object.values(import.meta.glob('./modules/*.ts', { eager: true })).forEach((i: any) => {
        const isNeedInstall = [
          UseModuleType.ROUTER,
        ].includes(i?.moduleType)

        if (isNeedInstall)
          i?.install(app)
      })
    })

    setTitle(TITLE)
    setWritingMode()

    const microStore = useMicroStore()
    if (!microStore.isMicro) {
      await setUserInfo()
      setTheme()
    }

    await setLanguages()
    if (!microStore.isMicro)
      await setApps(APP_CODE)
  }
  finally {
    setTimeout(() => {
      cancelFirstScreenLoading()
    }, 0)
  }
}
